#!/bin/bash

#need automake,autoconf,libtool,libssl-dev installed.
which automake
if [ 0 -ne $? ]; then
	echo "automake was not installed."
	exit 1
fi

which autoconf
if [ 0 -ne $? ]; then
	echo "autoconf was not installed."
	exit 1
fi

which libtoolize 
if [ 0 -ne $? ]; then
	echo "libtool was not installed."
	exit 1
fi
echo "automake & autoconf & libtool is installed."

if [ ! -f "/usr/include/openssl/ssl.h" ]; then
	echo "libssl-dev was not installed, libevent_openssl.a would be disabled."
else
	echo "libssl-dev was installed, libevent_openssl.a would be enabled."
fi

currentdir=$(cd "$(dirname "$0")"; pwd)
echo "build directory: ${currentdir}."

echo -e "\nbuild libevent..."
if [ ! -d "$currentdir/build" ]; then 
	mkdir "$currentdir/build"
else
	rm -rf ${currentdir}/build/*
fi 	

autoreconf

testarch=$(uname -m)
if [ $testarch = "mips64" ]; then
        sed -i 's/( sleep 1 ) &/sleep 1/1' ./configure
        sed -i 's/am_sleep_pid=$!/#am_sleep_pid=$!/1' ./configure
        echo "mips64 patch ok !"
fi

if [ $testarch = "loongarch64" ]; then
./configure CFLAGS=-fPIC --build=loongarch64-unknown-linux-gnu --disable-samples --enable-shared=no --enable-function-sections --prefix=/usr/local
else
./configure CFLAGS=-fPIC --disable-samples --enable-shared=no --enable-function-sections --prefix=/usr/local
fi
if [ $? -ne 0 ]; then exit 1; fi

make
make install DESTDIR=$currentdir/build

if [ ! -f "$currentdir/build/usr/local/lib/libevent_core.a" ]; then exit 1; fi
rm -rf ${currentdir}/../../../lib/libevent*.a
cp -v $currentdir/build/usr/local/lib/libevent_core.a ${currentdir}/../../../lib
cp -v $currentdir/build/usr/local/lib/libevent_pthreads.a ${currentdir}/../../../lib
cp -v $currentdir/build/usr/local/lib/libevent_extra.a ${currentdir}/../../../lib
if [ -f "$currentdir/build/usr/local/lib/libevent_openssl.a" ]; then
	cp -v $currentdir/build/usr/local/lib/libevent_openssl.a ${currentdir}/../../../lib
fi

make clean
rm -rf ${currentdir}/build/*

echo "====== libevent build success! ======"
exit 0
